package com.heima.test11;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveRunnable implements Runnable {
    //1 创建socket对象
    DatagramSocket ds;

    public ReceiveRunnable(DatagramSocket ds) {
       this.ds = ds;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //2 创建一个空的数据包对象 用来存放接收的数据
                byte[] bytes = new byte[1024];
                DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

                //3 接收数据
                ds.receive(dp);

                //4获取数据 转为字符串  打印
                System.out.println(new String(dp.getData(), 0, dp.getLength()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
